package com.hepinghospital.user.ui.activity.consult;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.adapter.ChatAdapter;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.eventbus.AlipaySuccessEvent;
import com.hepinghospital.user.eventbus.BillingStatusChangeEvent;
import com.hepinghospital.user.eventbus.WebSocket;
import com.hepinghospital.user.eventbus.WebSocketWrapper;
import com.hepinghospital.user.ui.activity.checkout.CheckoutOrderDetailActivity;
import com.hepinghospital.user.ui.activity.checkout.CheckoutPayActivity;
import com.hepinghospital.user.ui.activity.eyecheck.BigImageActivity;
import com.hepinghospital.user.ui.activity.home.AddRegistrationActivity;
import com.hepinghospital.user.ui.activity.prescription.AtyOrderMedicineDetailActivity;
import com.hepinghospital.user.ui.dialog.ApplyPermissionDialog;
import com.hepinghospital.user.ui.dialog.ReportDialog;
import com.hepinghospital.user.ui.dialog.SelectPicModeDialog;
import com.hepinghospital.user.ui.widget.AudioRecorderButton;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.PermissionsChecker;
import com.hepinghospital.user.util.ToastUtil;
import com.hepinghospital.user.util.UploadImageUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.BaseResponse;
import com.rest.response.ChatResponse;
import com.rest.response.CloudResponse;
import com.rest.response.IMListResponse;
import com.rest.response.Photo;
import com.rest.response.PicUploadResponse;
import com.rest.response.Prescription2Response;
import com.rest.response.RegistrationDetailResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.PreferencesHelper;
import jz.joyoung.robot.util.SoftKeyboardUtil;
import jz.joyoung.robot.util.TimeUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UriUtils;
import jz.joyoung.robot.util.UtilString;


/**
 * @Description: IM聊天界面
 * @Author: lzp
 * @CreateDate: 2023/10/23 9:22
 * @UpdateRemark: 更新说明
 */
public class ChatActivity extends BaseActivity {

    @BindView(R.id.chat_recyclerView)
    RecyclerView rvChat;
    @BindView(R.id.photo_recyclerView)
    RecyclerView rvPhoto;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_oneselfState)
    TextView tvOneselfState;
    @BindView(R.id.tv_patient_detail)
    TextView tvPatientDetail;
    @BindView(R.id.btn_show)
    FrameLayout btnShow;
    @BindView(R.id.edt_content)
    EditText edtContent;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.tv_pass)
    TextView tvPass;
    @BindView(R.id.tv_allergy)
    TextView tvAllergy;
    @BindView(R.id.tv_close)
    TextView tvClose;
    @BindView(R.id.ll_wait)
    LinearLayout llWait;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_remain_time)
    TextView tvRemainTime;
    @BindView(R.id.remain_time_container)
    ConstraintLayout remainTimeContainer;
    @BindView(R.id.pass_container)
    LinearLayout passContainer;
    @BindView(R.id.allergy_container)
    LinearLayout allergyContainer;
    @BindView(R.id.btn_yuyin)
    AudioRecorderButton btn_yuyin;
    @BindView(R.id.btn_add_photo)
    ImageView btnAddPhoto;
    @BindView(R.id.cl_bottom)
    ConstraintLayout clBottom;
    @BindView(R.id.nested_scrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.chk_show)
    CheckBox chkShow;
    @BindView(R.id.tv_doctor_name)
    TextView tvDoctorName;
    @BindView(R.id.tv_left_time)
    TextView tvLeftTime;
    @BindView(R.id.iv_doctor_head)
    ImageView ivDoctorHead;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;


    public static final int REQUEST_RECIVE_CALL = 0x033;
    public static final int REQUEST_MEDICINE = 0x044;

    PhotoAdapter adapter;
    private ChatAdapter chatAdapter;
    IMListResponse.IMItem imItem;
    WebSocketWrapper ws;
    CloudResponse cloud;
    List<Photo> photoList = new ArrayList<>();
    List<ChatResponse.Message> messageList = new ArrayList<>();

    String doctorUserId, doctorId, diagnoseId, patientAvatar, doctorPicture, createTime, acceptTime, conferenceID, patientSex;
    int diagType, chatFlag;
    MediaPlayer mediaPlayer;
    private CountDownTimer timer;

    private SelectPicModeDialog mSelectPicModeDialog = null;
    // 所需的全部权限
    static final String[] PICPERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    static final String[] VOICEPERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器

    //原图像 URI
    public Uri imgUriOri;
    //原图像 路径
    public static String imgPathOri;

    private boolean isMeeting = false;

    int current = 1;
    private int playingIndex = -1;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_chat;
    }

    @Override
    protected void initViews() {
        LinearLayoutManager manager = new LinearLayoutManager(ChatActivity.this, LinearLayoutManager.HORIZONTAL, false);
        rvPhoto.setLayoutManager(manager);
        adapter = new PhotoAdapter();
        rvPhoto.setAdapter(adapter);

        initChatList();
        initListener();

        refreshLayout.setEnableLoadMore(false);
        mPermissionsChecker = new PermissionsChecker(mContext);
    }

    private void initChatList() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rvChat.setLayoutManager(linearLayoutManager);
        chatAdapter = new ChatAdapter();
        rvChat.setAdapter(chatAdapter);
        chatAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (messageList.get(position).messageType == ChatResponse.IMAGE) {
                Bundle bundle = new Bundle();
                bundle.putString("url", messageList.get(position).src);
                bundle.putInt("type", 1);
                startActivity(BigImageActivity.class, bundle);
            } else if (messageList.get(position).messageType == ChatResponse.AUDIO) {
                if (mediaPlayer != null) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        chatAdapter.notifyItemChanged(playingIndex + chatAdapter.getHeaderLayoutCount(), ChatAdapter.PLAYLOAD_PAUSE);
                        if (position != playingIndex) {
                            mediaPlayer.reset();
                            playSound(position);
                        }
                    } else {
                        mediaPlayer.reset();
                        playSound(position);
                    }
                } else {
                    mediaPlayer = new MediaPlayer();
                    playSound(position);
                }
            } else if (messageList.get(position).messageType == ChatResponse.PRESCRIPTION) {
                Bundle bundle = new Bundle();
                bundle.putString("orderId", messageList.get(position).prescription.orderId);
                startActivity(AtyOrderMedicineDetailActivity.class, bundle);
            } else if (messageList.get(position).messageType == ChatResponse.CHECKOUT) {
                Bundle bundle = new Bundle();
                bundle.putString("orderId", messageList.get(position).checkList.orderId);
                bundle.putString("checkId", messageList.get(position).checkList.dataId);
                startActivityForResult(CheckoutOrderDetailActivity.class, bundle, 0x1234);
            }
        });
        chatAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.btn_pay) {
                Bundle bundle = new Bundle();
                bundle.putString("orderId", messageList.get(position).checkList.orderId);
                startActivity(CheckoutPayActivity.class, bundle);
            }
        });
    }

    private void initListener() {
        btnShow.setOnClickListener(v -> {
            if (chkShow.isChecked()) {
                chkShow.setChecked(false);
                passContainer.setVisibility(View.VISIBLE);
                allergyContainer.setVisibility(View.VISIBLE);
                rvPhoto.setVisibility(View.VISIBLE);
            } else {
                chkShow.setChecked(true);
                passContainer.setVisibility(View.GONE);
                allergyContainer.setVisibility(View.GONE);
                rvPhoto.setVisibility(View.GONE);
            }
        });

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            current = 1;
            messageList.clear();
            getMessageList(diagnoseId);
        });

        btn_yuyin.setAudioFinishRecorderListener((seconds, filePath) -> uploadVideo(filePath, (int) seconds));
        btn_yuyin.setOnLongClickMyListener(() -> {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        });
        edtContent.setOnClickListener(v -> {
            nestedScrollView.postDelayed(() -> {
                nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                edtContent.setFocusable(true);
                edtContent.setFocusableInTouchMode(true);
                edtContent.requestFocus();//获取焦点
            }, 500);
        });
        edtContent.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                sendTxtMessage();
            }
            return true;
        });
    }

    @Override
    protected void initData() {
        imItem = (IMListResponse.IMItem) getIntent().getSerializableExtra("obj");
        diagnoseId = getIntent().getStringExtra("diagnoseId");
        cloud = (CloudResponse) getIntent().getSerializableExtra("cobj");
        ws = (WebSocketWrapper) getIntent().getSerializableExtra("wsObj");
        if (ws != null) {
            //移动视频的在线消息
            diagnoseId = ws.diagnoseId;
            if (ws.meetingType == 0) {
                //是移动端拉起视频
                conferenceID = ws.conferenceNum;
            } else {
                //pc端的高清会议
                conferenceID = ws.conferenceID;
            }
            getRegistrationDetail(ws.diagnoseId);
        } else if (imItem != null) {
            diagnoseId = imItem.diagnoseId;
            getRegistrationDetail(imItem.diagnoseId);
        } else if (cloud != null) {
            diagnoseId = cloud.diagnoseId;
            getRegistrationDetail(cloud.diagnoseId);

        } else if (!UtilString.isEmpty(diagnoseId)) {
            getRegistrationDetail(diagnoseId);
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @OnClick({R.id.chk_voice, R.id.btn_add, R.id.btn_add_photo, R.id.cl_bottom, R.id.btn_send, R.id.btn_report})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.chk_voice:
                checkServiceRunning(mContext);
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(VOICEPERMISSIONS)) {
                    checkPermission("4", VOICEPERMISSIONS);
                } else {
                    switchTextAndAudio();
                }
                break;
            case R.id.btn_add:
                if (linearLayout.getVisibility() == View.GONE) {
                    linearLayout.setVisibility(View.VISIBLE);
                } else if (linearLayout.getVisibility() == View.VISIBLE) {
                    linearLayout.setVisibility(View.GONE);
                    edtContent.requestFocus();
                }
                nestedScrollView.postDelayed(() -> {
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }, 500);
                break;
            case R.id.btn_add_photo:
                checkServiceRunning(mContext);
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(PICPERMISSIONS)) {
                    checkPermission("3", PICPERMISSIONS);
                } else {
                    showSelectHeadPicDialog();
                }
                break;
            case R.id.cl_bottom:
                rvChat.postDelayed(() -> rvChat.scrollToPosition(messageList.size() - 1), 1500);
                break;
            case R.id.btn_send:
                sendTxtMessage();
                break;
            case R.id.btn_report:
                showReportDialog();
                break;
            default:
                break;
        }
    }


    private void getRegistrationDetail(String diagnoseId) {
        RestProxy.getInstance().getRegistrationDetail(diagnoseId, new BaseObserver<RegistrationDetailResponse>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(RegistrationDetailResponse registrationDetailResponse) {
                createTime = registrationDetailResponse.createTime;
                acceptTime = registrationDetailResponse.acceptTime;
                diagType = registrationDetailResponse.diagType;
                chatFlag = registrationDetailResponse.flag;
                patientSex = registrationDetailResponse.patientSex;
                tvTime.setText(createTime);
                startCountDownTimer(registrationDetailResponse.remainingTime);

                if (registrationDetailResponse.businessType == UIConstants.GRAPHIC_TYPE_1) {
                    tvTitle.setText(registrationDetailResponse.doctorName + getString(R.string.string_consult_b));
                } else if (registrationDetailResponse.businessType == UIConstants.GRAPHIC_TYPE_2) {
                    tvTitle.setText(registrationDetailResponse.doctorName + getString(R.string.string_referral_b));
                }
                if (diagType == 1) {
                    if (chatFlag != 0) {
                        tvDoctorName.setText(registrationDetailResponse.doctorName + "医生在线");
                    }
                    if (chatFlag == 2) {
                        tvDoctorName.setText(registrationDetailResponse.doctorName + "医生已下线");
                    }
                }
                doctorUserId = registrationDetailResponse.doctorUserId;
                doctorId = registrationDetailResponse.doctorId;
                BaseApplication.doctorAvatar = registrationDetailResponse.doctorPicture;
                if (registrationDetailResponse.resultList != null) {
                    if (registrationDetailResponse.resultList.size() == 0) {
                        //展示预约时上传的图片
                        rvPhoto.setVisibility(View.GONE);
                    }
                    photoList.clear();
                    photoList.addAll(registrationDetailResponse.resultList);
                    adapter.notifyDataSetChanged();
                }
                if (UtilString.isEmpty(registrationDetailResponse.cardType)) {
                    tvPatientDetail.setText(registrationDetailResponse.patientName + "  " + registrationDetailResponse.patientSex + "  " + registrationDetailResponse.patientAge);
                } else if ("1".equals(registrationDetailResponse.cardType)) {
                    tvPatientDetail.setText(registrationDetailResponse.patientName + "  " + registrationDetailResponse.patientSex + "  " + registrationDetailResponse.patientAge + "  自费卡");
                } else {
                    tvPatientDetail.setText(registrationDetailResponse.patientName + "  " + registrationDetailResponse.patientSex + "  " + registrationDetailResponse.patientAge + "  社保卡");
                }
//                tv_patient_detail.setText(registrationDetailResponse.data.doctorName + "  " + registrationDetailResponse.data.jobTitle + " " + (registrationDetailResponse.data.isPrescription == 0 ? "非处方" : "处方"));
                patientAvatar = registrationDetailResponse.patientAvatar;
                doctorPicture = registrationDetailResponse.doctorPicture;
                ImageLoaderHelper.getInstance().GlideCircleImageLoader(ChatActivity.this, registrationDetailResponse.doctorPicture, ivDoctorHead);
                tvOneselfState.setText(registrationDetailResponse.oneselfState);
                if (TextUtils.isEmpty(registrationDetailResponse.pastHistory)) {
                    tvPass.setText("无");
                } else {
                    tvPass.setText(registrationDetailResponse.pastHistory);
                }
                if (TextUtils.isEmpty(registrationDetailResponse.allergyHistory)) {
                    tvAllergy.setText("无");
                } else {
                    tvAllergy.setText(registrationDetailResponse.allergyHistory);
                }
                if (registrationDetailResponse.flag == 2) {
                    tvClose.setVisibility(View.VISIBLE);
                    tvClose.setText("问诊已结束");
                    clBottom.setVisibility(View.INVISIBLE);
                    llWait.setVisibility(View.GONE);
//                    remainTimeContainer.setVisibility(View.GONE);
                } else if (registrationDetailResponse.flag == 0) {
                    //等待
                    clBottom.setVisibility(View.INVISIBLE);
                    if (diagType == 1) {
                        llWait.setVisibility(View.VISIBLE);
                    } else {
                        llWait.setVisibility(View.GONE);
                    }
                } else if (registrationDetailResponse.flag == 1) {
                    clBottom.setVisibility(View.VISIBLE);
                    llWait.setVisibility(View.GONE);
                }
                if (ws != null) {
                    PreferencesHelper.getInstance().set(ChatActivity.this, "isShowPhone", true);
                    Bundle bundle = new Bundle();
                    bundle.putString("doctor", registrationDetailResponse.doctorName + "  " + registrationDetailResponse.jobTitle);
                    bundle.putString("doctorPicture", registrationDetailResponse.doctorPicture);
                    startActivityForResult(PhoneActivity.class, bundle, REQUEST_RECIVE_CALL);
                }
                getMessageList(diagnoseId);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ChatActivity.this, e);
            }
        });
    }

    /**
     * 查看聊天记录
     *
     * @time 2020/12/7 10:47
     */
    private void getMessageList(String diagnoseId) {
        RestProxy.getInstance().getChatList(diagnoseId, current + "", new Observer<ChatResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ChatResponse chatResponse) {
                messageList.clear();
                if (chatResponse.records != null) {
                    Collections.reverse(chatResponse.records);
                    messageList.addAll(chatResponse.records);
                    if (diagType == 1) {
                        if (chatFlag != 0) {
                            if (chatAdapter.getHeaderLayoutCount() == 0) {
                                chatAdapter.addHeaderView(LayoutInflater.from(mContext).inflate(R.layout.header_chat, rvChat, false));
                            }
                        }
                        if (chatFlag == 2) {
                            if (chatAdapter.getFooterLayoutCount() == 0) {
                                chatAdapter.addFooterView(LayoutInflater.from(mContext).inflate(R.layout.footer_chat, rvChat, false));
                            }
                        }
                    }
                }
                chatAdapter.setList(messageList);
                if (current == 1) {
                    rvChat.postDelayed(() -> {
                        nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                    }, 1000);
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(ChatActivity.this, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }

    private void sendTxtMessage() {
        checkServiceRunning(mContext);
        if (TextUtils.isEmpty(edtContent.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "不能发送空白消息");
            return;
        }
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
        ChatResponse.Message message = new ChatResponse().new Message();
        String clientId = TimeUtil.getClientId();
        message.messageId = clientId;
        message.messageType = ChatResponse.TEXT;
        message.fromType = ChatResponse.PATIENT;
        message.flag = ChatResponse.SENDING;
        message.content = edtContent.getText().toString();
        message.sendTime = df.format(new Date());
        messageList.add(message);
        chatAdapter.addData(message);
        nestedScrollView.postDelayed(() -> {
            nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
            edtContent.setFocusable(true);
            edtContent.setFocusableInTouchMode(true);
            edtContent.requestFocus();//获取焦点
            edtContent.setText("");
        }, 500);
        WebSocket webSocket = new WebSocket.Builder().content(edtContent.getText().toString()).docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(doctorUserId).msgType(ChatResponse.TEXT).eventFlag(1).clientId(clientId).build();
        EventBus.getDefault().postSticky(webSocket);
    }

    private void playSound(int position) {
        try {
            mediaPlayer.setDataSource(messageList.get(position).content);
            mediaPlayer.prepareAsync(); // 准备文件
            mediaPlayer.setOnPreparedListener(mp -> {
                // 装载完毕回调
                mediaPlayer.start();
                playingIndex = position;
                chatAdapter.notifyItemChanged(position + chatAdapter.getHeaderLayoutCount(), ChatAdapter.PLAYLOAD_SPEAKING);
            });
            mediaPlayer.setOnCompletionListener(mp -> {
                playingIndex = -1;
                chatAdapter.notifyItemChanged(position + chatAdapter.getHeaderLayoutCount(), ChatAdapter.PLAYLOAD_PAUSE);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void finishMeeting() {
        RestProxy.getInstance().finishMeeting(BaseApplication.currentUserId, diagnoseId, doctorUserId, conferenceID, ws.meetingType + "", new BaseObserver<String>() {
            @Override
            public void onSuccess(String result) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            //data的返回值根据
            switch (requestCode) {
                case AddRegistrationActivity.REQUEST_OPEN_CAMERA:
                    uploadPic(imgPathOri);
                    break;
                case AddRegistrationActivity.REQUEST_GALLERY:
                    if (data != null) {
                        Uri imgUriSel = data.getData();
                        String imgPathSel = UriUtils.formatUri(this, imgUriSel);
                        uploadPic(imgPathSel);
                    }
                    break;
                case REQUEST_RECIVE_CALL:
                    //接受视频会议,加入会议
                    isMeeting = true;
                    break;
                case REQUEST_MEDICINE:
                    messageList.clear();
                    current = 1;
                    getMessageList(diagnoseId);
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (requestCode == REQUEST_RECIVE_CALL) {
                //拒绝会议视频
                finishMeeting();
            }
        }
    }


    private void uploadVideo(String imgPathSel, int time) {
        RestProxy.getInstance().uploadVideo(new File(imgPathSel), new Observer<PicUploadResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(PicUploadResponse picUploadResponse) {
                ChatResponse.Message message = new ChatResponse().new Message();
                @SuppressLint("SimpleDateFormat")
                SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
                String clientId = TimeUtil.getClientId();
                message.messageId = clientId;
                message.messageType = ChatResponse.AUDIO;
                message.fromType = ChatResponse.PATIENT;
                message.flag = ChatResponse.SENDING;
                message.content = picUploadResponse.shareUrl;
                message.src = picUploadResponse.shareUrl;
                message.sendTime = df.format(new Date());
                message.time = time;
                messageList.add(message);
                chatAdapter.addData(message);
                rvChat.postDelayed(() -> {
                    rvChat.scrollToPosition(0);
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                }, 1000);
                WebSocket webSocket = new WebSocket.Builder().content(picUploadResponse.shareUrl).docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(doctorUserId).picType("wav").msgType(ChatResponse.AUDIO).eventFlag(1).clientId(clientId).time(time).build();
                EventBus.getDefault().postSticky(webSocket);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ChatActivity.this, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }


    public void switchTextAndAudio() {
        if (btn_yuyin.getVisibility() == View.GONE) {
            btn_yuyin.setVisibility(View.VISIBLE);
            edtContent.setVisibility(View.GONE);
            SoftKeyboardUtil.hideKeyboard(edtContent);
        } else {
            btn_yuyin.setVisibility(View.GONE);
            edtContent.setVisibility(View.VISIBLE);
            SoftKeyboardUtil.showSoftInput(edtContent);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PreferencesHelper.getInstance().set(ChatActivity.this, "isShowPhone", false);
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

        if (timer != null) {
            timer.cancel();
        }
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WebSocket webSocket) {
        //eventFlag == 0 接收消息
        if (webSocket.eventFlag == 0) {
            if (webSocket.diagnoseId.equals(diagnoseId)) {
                if (webSocket.msgType != ChatResponse.PRESCRIPTION && webSocket.msgType != ChatResponse.CHECKOUT) {
                    ChatResponse.Message message = new ChatResponse().new Message();
                    message.messageId = TimeUtil.getClientId();
                    message.messageType = webSocket.msgType;
                    message.content = webSocket.content;
                    message.src = webSocket.src;
                    if (!TextUtils.isEmpty(webSocket.createTime)) {
                        //2023-10-24 09:11
                        message.sendTime = webSocket.createTime.substring(10);
                    }
                    message.time = webSocket.time;
                    message.fromType = 1;
                    messageList.add(message);
                    chatAdapter.addData(message);
                    nestedScrollView.postDelayed(() -> {
                        nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }, 500);
                } else {
                    //msgType==6代表处方消息
                    if (!UtilString.isEmpty(webSocket.preId)) {
//                        getPrescription(webSocket.preId);
                    }
                    if (webSocket.msgType == ChatResponse.CHECKOUT) {
                        refreshLayout.autoRefresh();
                    }
                }
                WebSocket webSocket2 = new WebSocket();
                webSocket2.cmd = 24;
                webSocket2.diagnoseId = webSocket.diagnoseId;
                webSocket2.to = webSocket.to;
                webSocket2.msgId = webSocket.id;
                webSocket2.eventFlag = 4;
                EventBus.getDefault().postSticky(webSocket2);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent2(WebSocketWrapper webSocket) {
        if (webSocket.cmd == UIConstants.WEBSOCKET_CMD_100) {
            finish();
        } else if (webSocket.cmd == UIConstants.WEBSOCKET_CMD_108) {
            getRegistrationDetail(diagnoseId);
        } else if (webSocket.cmd == UIConstants.WEBSOCKET_CMD_110 || webSocket.cmd == UIConstants.WEBSOCKET_CMD_112 || webSocket.cmd == UIConstants.WEBSOCKET_CMD_211 ||
                webSocket.cmd == UIConstants.WEBSOCKET_CMD_212) {
            current = 1;
            messageList.clear();
            getMessageList(diagnoseId);
        } else if (webSocket.code == 10000 || webSocket.code == 10001) {
            for (int i = messageList.size() - 1; i >= 0; i--) {
                if (!TextUtils.isEmpty(messageList.get(i).messageId) && messageList.get(i).messageId.equals(webSocket.clientId)) {
                    messageList.get(i).flag = 0;
                    chatAdapter.notifyItemChanged(i + chatAdapter.getHeaderLayoutCount(), ChatAdapter.PLAYLOAD_SENDSUCCESS);
                    break;
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAlipaySuccessEvent(AlipaySuccessEvent event) {
        refreshLayout.autoRefresh();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBillingStatusChangeEvent(BillingStatusChangeEvent event) {
        refreshLayout.autoRefresh();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.e("onnewintent", "onnewintent");
        long userid = intent.getLongExtra("userid", 0);
//        ws = (WebSocketWrapper) intent.getSerializableExtra("wsObj");
//        if (ws != null) {
//            diagnoseId = ws.diagnoseId;
//            startActivityForResult(PhoneActivity.class, REQUEST_RECIVE_CALL);
//        }
        if (userid != 0) {
//            checkPermissionAndShow( userid );
        } else {
//            Intent intents = new Intent( ChatActivity1.this, FloatingService.class );
//            stopService( intents );
        }
        super.onNewIntent(intent);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            finish();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }


    private void getPrescription(String preId) {
        LogUtil.e("处方id----", preId + "");
        RestProxy.getInstance().getPrescription(preId, new Observer<Prescription2Response>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Prescription2Response prescriptionResponse) {
                boolean isHave = false;
                for (ChatResponse.Message message : messageList) {
                    if (message.prescription.prescriptionId.equals(preId)) {
                        message.prescription = prescriptionResponse;
                        isHave = true;
                        break;
                    }
                }
                if (isHave) {
                    chatAdapter.notifyDataSetChanged();
                } else {
                    ChatResponse.Message message = new ChatResponse().new Message();
                    message.messageId = TimeUtil.getClientId();
                    message.messageType = ChatResponse.PRESCRIPTION;
                    message.fromType = ChatResponse.DOCTOR;
                    message.flag = ChatResponse.SENDSUCCESS;
                    message.prescription = prescriptionResponse;
                    messageList.add(message);
                    chatAdapter.addData(message);
                }
                nestedScrollView.postDelayed(() -> {
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }, 500);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(ChatActivity.this, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void startCountDownTimer(String remainPayTime) {
        if (TextUtils.isEmpty(remainPayTime)) {
            return;
        }
        Log.e("倒计时===", remainPayTime);
        int parseInt = 0;
        try {
            parseInt = Integer.parseInt(remainPayTime);
        } catch (Exception e) {
            return;
        }
        timer = new CountDownTimer(parseInt, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvLeftTime.setText(millisUntilFinished / 60000 / 60 + "时" + millisUntilFinished / 60000 % 60 + "分" + (millisUntilFinished / 1000) % 60 + "秒");
            }

            @Override
            public void onFinish() {
            }
        };
        timer.start();
    }

    /**
     * 举报弹框
     */
    private void showReportDialog() {
        ReportDialog refundDialog = ReportDialog.newInstance();
        refundDialog.setmListener(new ReportDialog.OnItemClickListener() {
            @Override
            public void onConfirm(String reason) {
                reportViolations(reason);
            }

            @Override
            public void onCancel() {

            }
        });
        refundDialog.show(getSupportFragmentManager(), "ReportDialog");
    }

    /**
     * 举报
     *
     * @param reason 原因
     */
    public void reportViolations(String reason) {
        RestProxy.getInstance().reportViolations(diagnoseId, reason, new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String baseResponse) {
                ToastUtil.showToast(mContext, "举报成功");
                getRegistrationDetail(diagnoseId);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(ChatActivity.this).inflate(R.layout.item_photo2, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putString("url", photoList.get(position).url);
                bundle.putInt("type", 1);
                ChatActivity.this.startActivity(BigImageActivity.class, bundle);
            });
            ImageLoaderHelper.getInstance().GlideImageLoader(ChatActivity.this, photoList.get(position).thumbnailUrl, holder.img);
        }

        @Override
        public int getItemCount() {
            return photoList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            ImageView img;

            Holder(View itemView) {
                super(itemView);
                img = itemView.findViewById(R.id.image);
            }
        }
    }

    private void uploadPic(String imgPathSel) {
        showLoadingDialog(this);
        UploadImageUtil.uploadPic("9", "92", imgPathSel, "1", new UploadImageUtil.UploadCallBack() {
            @Override
            public void success(PicUploadResponse picUploadResponse) {
                try {
                    runOnUiThread(() -> {
                        dismissLoadingDialog();
                        ChatResponse.Message message = new ChatResponse().new Message();
                        @SuppressLint("SimpleDateFormat")
                        SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
                        message.messageType = ChatResponse.IMAGE;
                        String clientId = TimeUtil.getClientId();
                        message.messageId = clientId;
                        message.fromType = ChatResponse.PATIENT;
                        message.flag = ChatResponse.SENDING;
                        message.content = picUploadResponse.ShareThumbnailUrl == null ? picUploadResponse.shareThumbnailUrl : "";
                        message.src = picUploadResponse.shareUrl;
                        message.sendTime = df.format(new Date());
                        messageList.add(message);
                        chatAdapter.addData(message);
                        nestedScrollView.postDelayed(() -> {
                            nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        }, 500);
                        WebSocket webSocket = new WebSocket.Builder().content(picUploadResponse.ShareThumbnailUrl == null ? picUploadResponse.shareThumbnailUrl : "").docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(doctorUserId).picType("jpeg").src(picUploadResponse.shareUrl).msgType(1).eventFlag(1).clientId(clientId).build();
                        EventBus.getDefault().postSticky(webSocket);
                    });

                } catch (Exception e) {
                    dismissLoadingDialog();
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void fail() {
                dismissLoadingDialog();
            }
        });
    }

    @SuppressLint("CheckResult")
    private void checkPermission(String status, String[] pArray) {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance(status, true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(ChatActivity.this);
                permissions.request(pArray).subscribe(granted -> {
                    if (granted) {
                        if ("3".equals(status)) {
                            showSelectHeadPicDialog();
                        } else if ("4".equals(status)) {
                            switchTextAndAudio();
                        }
                    } else {
                        if ("3".equals(status)) {
                            ToastUtil.showToast(mContext, "请同意相册和存储权限，否则功能无法使用");
                        } else if ("4".equals(status)) {
                            ToastUtil.showToast(mContext, "请同意语音和存储权限，否则功能无法使用");
                        }
                        startNotificationSetting(mContext);
                    }
                });
            }

            @Override
            public void onCancel() {
            }
        });
    }

    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            // 初始化点击头像弹出的对话框
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener(new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile(oriPhotoFile);
                    } else {
                        imgUriOri = FileProvider.getUriForFile(ChatActivity.this, UIConstants.FILE_PROVIDER_URI, oriPhotoFile);
                    }
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(intent, AddRegistrationActivity.REQUEST_OPEN_CAMERA);
                }

                @Override
                public void pickFromAlbumClick() {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, AddRegistrationActivity.REQUEST_GALLERY);
                }
            });
        }
        mSelectPicModeDialog.show(getSupportFragmentManager(), "SelectPicModeDialog");
    }

    /**
     * 创建原图像保存的文件
     *
     * @return
     * @throws IOException
     */
    protected File createOriImageFile() throws IOException {
        String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }
}
